package com.yubest.servletjsp.util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestUtil {

    private static final String CODE_KEY = "code";

    private static final String DATA_KEY = "data";

    private static final String MSG_KEY = "msg";

    /**
     * 成功状态码
     */
    private static final Integer SUCCESS_CODE = 200;

    /**
     * 失败状态码
     */
    private static final Integer ERROR_CODE = 1000;

    public static void success(String page, Object data, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute(CODE_KEY, SUCCESS_CODE);
        request.setAttribute(DATA_KEY, data);
        request.setAttribute(MSG_KEY, "请求成功");
        if (null != page) {
            request.getRequestDispatcher(page).forward(request, response);
//            response.sendRedirect(request.getContextPath() + page);
        }
    }

    public static void error(String page, String msg, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setAttribute(CODE_KEY, ERROR_CODE);
        request.setAttribute(DATA_KEY, null);
        request.setAttribute(MSG_KEY, null != msg ? msg : "请求失败");
        if (null != page) {
            request.getRequestDispatcher(page).forward(request, response);
//            response.sendRedirect(request.getContextPath() + page);
        }
    }
}
